/**
 * Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 * Platypus is (c) Copyright 2009-12 Pacific Data Works LLC. All Rights Reserved.
 * Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */

package org.pz.platypus;

import org.pz.platypus.commandline.*;
import org.pz.platypus.exceptions.StopExecutionException;
import org.pz.platypus.utilities.PlatypusHomeDirectory;
import org.pz.platypus.parser.*;

/**
 * The main line. Called by Platypus.java
 * @author alb
 */

public class Main
{
    ClParser commandLine;
    GDD gdd;

    public void run( String[] args )
    {
        displayCopyright();
        try {
            // set up data structures
            PlatypusHomeDirectory homeDir = new PlatypusHomeDirectory( args );
            gdd = new GDD( homeDir.get() );
            Literals lits = new Literals( homeDir.get(), gdd );
            gdd.setupGdd( lits );

            // initial processing of command line
            commandLine = new ClParser( args );
            ClProcessor clproc = new ClProcessor( commandLine, args, gdd );
            clproc.processVerbosityOptions();

            // load config file and command file
            gdd.configFile = new ConfigFile( new ConfigLocator( gdd ), gdd );
            gdd.commandTable.load();

            // main command-line processing
            String pluginLocation = clproc.process();

            // if there's an output plugin to run, load it up and run it
            if( pluginLocation != null ) {
                // do we first need to parse the input file?
                if( new ParseVerifier().isNeeded() ) {
                    new DocumentParser( gdd ).parseFile();
                }
                PluginLoader pluginLoader = new PluginLoader( pluginLocation, gdd );
                pluginLoader.runPlugin();
                showTokens( gdd );
            }
        } catch( StopExecutionException see ) {
            showTokens( gdd );
            return; // all exceptions are a request to exit. Any error messages have already been shown.
        }
    }

    /**
     * Display the copyright notice on the console.
     */
    private void displayCopyright( )
    {
        CopyrightNotice copyright = new CopyrightNotice();
        System.out.println( "Platypus v. 0.2.7 " + copyright.toString() );
    }

    /**
     * Show any token lists, if -vverbose is specified
     */
    private void showTokens( GDD gdd )
    {
        if( gdd != null && gdd.clVVerbose && gdd.docTokens != null )
            gdd.docTokens.dump( gdd );
    }
}
